package com.xyg.controller;

import com.xyg.pojo.Result;
import com.xyg.pojo.User;
import com.xyg.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

@RestController
@RequestMapping( "/api/user" )
public class UserController {

    @Autowired
    private UserService userService;

    //* 查询当前用户信息: /api/user/me
    @GetMapping( "/me" )
    public Result< User > getCurrentUser ( @RequestParam String username ) {
        if ( username == null || username.isEmpty() ) {
            return Result.failure( 400, "用户名不能为空" );
        }
        Optional< User > currentUser = userService.findByUsername( username );
        return currentUser.map( user -> Result.success( "查询当前用户信息成功", user ) )
                .orElseGet( () -> Result.failure( 404, "用户未找到" ) );
    }

    //* 更新当前用户信息: /api/user/update
    @PutMapping( "/update" )
    public Result< User > updateCurrentUser ( @RequestBody User user ) {
        if ( user == null || user.getId() == null || user.getId().isEmpty() ) {
            return Result.failure( 400, "用户ID不能为空" );
        }
        User updatedUser = userService.updateById( user.getId(), user );
        return Result.success( "更新当前用户信息成功", updatedUser );
    }

}
